<template>
    <oa-page title="考勤打卡" :enable-right="false">
        <div class="card">
            <div class="card-title">上班时间：9:00</div>
            <button @click="check(true)" v-if="show_start" :disabled="can_start" class="btn-class"
                    :class="{'warn':is_late}">
                <label class="btn-title">{{btn_start}}</label>
                <label class="btn-time">{{hour}}:{{min}}:{{second}}</label>
            </button>
            <div v-show="!show_start" class="start_time">
                <img src="../assets/checkmark.png" class="check"/>
                <p class="tips">打卡成功</p>
                <p class="time">打卡时间</p>
                <p>{{start_time}}</p>
                <p>{{start_address}}</p>
            </div>
            <div @click="reload(true)" v-show="!show_start" class="reload">
                更新打卡
            </div>
            <label v-show="addressItem.address!=''&&show_start" class="wifi-state"
                   :class="in_home?'in-home':'out-home'">{{in_home?"已进入考勤打卡范围":'未在考勤打卡范围内'}}</label>
            <label v-show="in_location&&show_start" class="wifi-state">{{location_msg}}</label>


            <div class="border-bottom-1px"></div>
            <div class="card-title" style="margin-top: 12px">下班时间：18:00</div>
            <button @click="check(false)" v-if="show_end" :disabled="can_start" class="btn-class"
                    :class="{'warn':is_early}">
                <label class="btn-title">{{btn_end}}</label>
                <label class="btn-time">{{hour}}:{{min}}:{{second}}</label>
            </button>
            <div v-show="end_time.length > 0 && !show_end" class="start_time">
                <img src="../assets/checkmark.png" class="check"/>
                <p class="tips">打卡成功</p>
                <p class="time">打卡时间</p>
                <p>{{end_time}}</p>
                <p>{{end_address}}</p>
            </div>
            <div @click="reload(false)" v-show="!show_end" class="reload">
                更新打卡
            </div>
            <label v-show="addressItem.address!=''&&show_end" class="wifi-state" :class="in_home?'in-home':'out-home'">{{in_home?"已进入考勤打卡范围":'未在考勤打卡范围内'}}</label>
            <label v-show="in_location&&show_end" class="wifi-state">{{location_msg}}</label>
        </div>
        <transition enter-active-class="animated fadeIn"
                    leave-active-class="animated fadeOut">
            <div class="modal-mask" ref="mask" v-if="show_modal">

            </div>
        </transition>
        <transition enter-active-class="animated bounceIn"
                    leave-active-class="animated bounceOut">
            <div class="modal-content" ref="mask" v-if="show_modal">
                <div class="modal-dialog">
                    <label class="title">确定进行{{not_message}}打卡</label>
                    <div class="card-time">
                        <div class="card-tips">
                            打卡时间：{{card_time}}
                        </div>
                        <div class="card-tips">
                            打卡地址：{{addressItem.address}}
                        </div>
                    </div>
                    <textarea v-model="reason" placeholder=" 请填写打卡备注（选填） "></textarea>
                    <div class="btn-bottom">
                        <div class="btn-default" @click="show_modal = false">
                            不打卡
                        </div>
                        <div class="btn-default" @click="uploadCardInfo">
                            确定
                        </div>
                    </div>
                </div>
            </div>
        </transition>
    </oa-page>
</template>

<script>
    import OaPage from "../components/oa-page";
    import Coordinate, {getConfig, getTokenInfo} from "../config";

    export default {
        components: {OaPage},
        name: "location",
        data() {
            return {
                reason: '',
                hour: "",
                min: "",
                second: "",
                card_time: "",
                is_start : false,
                location_msg: "正在定位中",
                btn_start: "上班打卡",
                btn_end: "下班打卡",
                not_message: "",
                is_late: false,
                is_early: false,
                show_modal: false,
                wifi_name: "",
                can_start: true,
                show_start: true,
                show_end: false,
                clock_timer: null,
                location_timer: null,
                in_wifi: false,
                in_location: false,
                temp_address: "",
                start_time: "",
                start_address: "",
                end_address: "",
                end_time: "",
                in_home: true,
                addressItem: {
                    latitude: "",
                    longitude: "",
                    address: ""
                }
            }
        },
        mounted() {
            try {
                WifiWizard.listNetworks((res) => {
                    console.log(res)
                    // alert(res)
                }, (error) => {
                    console.log(error)
                })
            } catch (e) {
                console.log(e)
            }

            this.runTimeLoop()
        },
        beforeRouteLeave(to, form, next) {
            this.stopTimeLoop()
            console.log("离开了")
            next()
        },


        methods: {

            convertDateFromString(dateString) {
                if (dateString) {
                    dateString = dateString.replace(/-/g, "/");
                    let date = new Date(dateString);
                    return date;
                }
            },
            reload(isStart) {
                let key = isStart ? "start_time" : "end_time"
                localStorage.removeItem(key)

            },

            afterEnter() {

            },

            runTimeLoop() {
                this.clock_timer = setInterval(() => {
                    this.showTime()
                }, 1000)
                this.location_timer = setInterval(() => {
                    this.goLocation()
                }, 1000)
            },

            goLocation() {

                if (this.in_wifi) {

                } else {
                    this.in_location = true
                    try {
                        if (this.location_msg != this.temp_address) {
                            this.location_msg = "正在定位中，请稍后..."
                        }
                        let Coordinate_range = Coordinate.Coordinate_range;
                        baidumap_location
                            .getCurrentPosition((result) => {
                                // console.log(JSON.stringify(result, null, 4));
                                //此处获取经纬度
                                console.log(result)
                                this.location_msg = result.addr
                                this.temp_address = result.addr
                                this.addressItem.latitude = result.latitude;
                                this.addressItem.longitude = result.longitude;
                                this.addressItem.address = result.addr
                                this.can_start = false
                                this.in_home = (this.addressItem.longitude <= Coordinate_range.x1 && this.addressItem.longitude >= Coordinate_range.x0 && this.addressItem.latitude <= Coordinate_range.y1 && this.addressItem.latitude >= Coordinate_range.y0);
                            }, (error) => {
                                this.can_start = true
                            });
                    } catch (e) {
                        // console.log(e);
                        this.location_msg = "定位失败，请检查GPS或网络是否打开"

                    }

                }
            }
            ,

            stopTimeLoop() {
                clearInterval(this.clock_timer)
                clearInterval(this.location_timer)
            }
            ,

            showTime() {
                let date = new Date();
                let hour = date.getHours();
                let min = date.getMinutes()
                let second = date.getSeconds()
                this.hour = hour + ""
                this.min = min < 10 ? `0${min}` : min
                this.second = second < 10 ? `0${second}` : second
                if (hour >= 9) {
                    this.btn_start = "迟到打卡"
                    this.is_late = true
                } else if (btn < 9) {
                    this.btn_start = "上班打卡"
                    this.is_late = false
                }
                if (hour < 18) {
                    this.btn_end = "早退打卡"
                    this.is_early = true
                } else {
                    this.is_early = false
                    this.btn_end = "下班打卡"

                }
                this.checkIsCard(hour, date)


            },
            checkIsCard(hour, date) {
                let now = date

                let start_time = localStorage.getItem("start_time")
                let end_time = localStorage.getItem("end_time")
                this.start_address = localStorage.getItem("start_address")
                this.end_address = localStorage.getItem("end_address")

                if (start_time != null) {
                    let start = this.convertDateFromString(start_time)

                    if (start.getDate() == now.getDate()) {
                        this.start_time = start.getHours() + ":" + (start.getMinutes() < 10 ? `0${start.getMinutes()}` : start.getMinutes())
                        this.show_start = false

                    } else {
                        this.start_time = ""
                        this.show_start = true
                    }
                } else {
                    this.start_time = ""
                    this.show_start = true
                }
                // if (hour > 14) {
                let end = this.convertDateFromString(end_time)
                if (end_time != null && end_time != "") {
                    if (end.getDate() == now.getDate()) {
                        this.end_time = end.getHours() + ":" + (end.getMinutes() < 10 ? `0${end.getMinutes()}` : end.getMinutes())
                        this.show_end = false
                    } else {
                        this.end_time = "今日未打卡"
                        this.show_end = true
                    }
                } else {
                    this.end_time = ""
                    this.show_end = true
                }
                // } else {
                //     this.end_time = ""
                //     this.show_end = false
                // }
            },
            uploadCardInfo() {
                this.show_modal = false
                let date = new Date()
                let config = getConfig();
                let tokenInfo = getTokenInfo();
                const toast = this.$createToast({
                    txt: '正在打卡',
                    type: 'loading',
                    time: 0,
                })
                toast.show();
                let url = config.rootUrl +
                    `/OA_Attendence/UserCard?type=app&Dcqtech_Token=${tokenInfo.token.TokenId}&in_out=${this.in_home ? 1 : 0}&lat=${this.addressItem.latitude}&lon=${this.addressItem.longitude}&address=${this.addressItem.address}&why=${this.reason}`;
                this.$get(url).then((res) => {
                    if (this.is_start) {
                        localStorage.setItem("start_address", this.addressItem.address)
                        localStorage.setItem("start_time", date.pattern("yyyy-MM-dd hh:mm:ss"))
                    } else {
                        localStorage.setItem("end_address", this.addressItem.address)
                        localStorage.setItem("end_time", date.pattern("yyyy-MM-dd hh:mm:ss"))
                    }
                    toast.hide();
                    this.$createDialog({
                        type: 'alert',
                        title: '成功',
                        content: '打卡成功',
                        icon: 'cubeic-ok',
                        onConfirm: () => {

                        }
                    }).show()
                }).catch((error) => {
                    toast.hide();
                    this.$createToast({
                        txt: '网络错误',
                        type: 'error',
                        time: 1500,
                    })
                })
            },
            check(is_start) {
                this.is_start = is_start;
                // if (is_start) {
                //     localStorage.setItem("start_time", date.pattern("yyyy-MM-dd hh:mm:ss"))
                // } else {
                //     localStorage.setItem("end_time", date.pattern("yyyy-MM-dd hh:mm:ss"))
                // }
                if (this.is_early || this.is_late || !this.in_home) {
                    if (this.is_late && is_start) {
                        this.not_message = "迟到"
                    } else if (!this.is_late && is_start && !this.in_home) {
                        this.not_message = "外勤"
                    } else if (this.is_early && !is_start) {
                        this.not_message = "早退"
                    }
                    this.card_time = new Date().pattern("yyyy-MM-dd hh:mm:ss")
                    this.show_modal = true

                } else {
                    this.uploadCardInfo()
                }


            }
        }

    }
</script>

<style scoped lang="less">
    /*.fade-enter-active, .fade-leave-active {*/
    /*transition: all 1s;*/
    /*}*/

    /*.fade-enter, .fade-leave-to !* .fade-leave-active below version 2.1.8 *! {*/

    /*}*/

    .card {
        background: #fff;
        border-radius: 5px;
        margin: 16px;
        padding: 16px;
        box-shadow: #e0e0e0 2px 2px 2px;
        text-align: center;
        .card-title {
            font-size: 12px;
            color: #888888;
        }
        .border-bottom-1px {
            margin-top: 8px;
            border-bottom: dashed 1px #e0e0e0;
        }
        .wifi-state {
            display: block;
            font-size: 14px;
            color: #f0ad27;
            margin-top: 12px;
            &.in-home {
                color: #39b338;
            }
            &.out-home {
                color: #41a6f0;
            }
        }
        .reload {
            color: #fff;
            width: 100px;
            height: 32px;
            line-height: 32px;
            border-radius: 8px;
            margin: auto;
            margin-bottom: 10px;
            margin-top: 10px;
            background: #41a6f0;
            &:active {
                background: darken(#41a6f0, 10%);
            }
        }
        .start_time {
            display: block;
            font-size: 14px;
            font-weight: bold;
            color: #888888;
            margin-top: 8px;
            text-align: center;
            .check {
                width: 64px;
                height: 64px;
            }
            .tips {
                line-height: 24px;
                font-size: 16px;
                color: #39b338;
                margin-top: 8px;
            }
            .time {
                font-size: 14px;
                color: #f0be20;
                margin-top: 8px;
                margin-bottom: 8px;
            }
        }
        .btn-class {
            margin-top: 12px;
            background: #41a6f0;
            width: 140px;
            height: 140px;
            border: solid 0 transparent;
            text-align: center;
            vertical-align: middle;
            color: #fff;
            border-radius: 50%;
            outline: none;
            box-shadow: rgba(65, 166, 240, 0.65) 2px 2px 2px;

            &:disabled {
                background: #999999;
                box-shadow: rgba(105, 105, 105, 0.65) 2px 2px 2px;
                &.warn {
                    background: #999999;
                    box-shadow: rgba(133, 127, 123, 0.65) 2px 2px 2px;
                    &:active {
                        background: #999999;
                    }
                }
            }

            &.warn {
                background: #f0ad27;
                box-shadow: rgba(240, 190, 32, 0.65) 2px 2px 2px;
                &:active {
                    background: darken(#f0ad27, 10%);
                }
            }
            .btn-title {
                display: block;
                font-size: 18px;
            }
            .btn-time {
                display: block;
                font-size: 14px;
                color: #e0e0e0;
            }
            &:active {
                background: darken(#41a6f0, 10%);
            }
        }
    }

    .modal-dialog {
        position: absolute;
        width: 320px;
        height: 340px;
        background: #fff;
        display: flex;
        flex-direction: column;
        .title {
            padding: 8px 12px;
            font-size: 18px;
            color: #2c2c2c;
            text-align: center;
        }
        .card-time {
            font-size: 14px;
            color: #2c2c2c;
            .card-tips {
                color: #888888;
                line-height: 32px;
                margin-left: 12px;
                margin-right: 12px;
            }
            background: #f0f0f0;
            border-bottom: solid 1px #e0e0e0;
            border-top: solid 1px #e0e0e0;
        }
        > textarea {
            flex: 1 0 auto;
            border: none;
            outline: none;
            padding: 10px;
            font-size: 16px;
            margin-left: 0;
            margin-right: 0;
            color: #2c2c2c;
            &::-webkit-input-placeholder {
                color: #888888;

            }
        }
        .btn-bottom {
            height: 44px;
            border-top: solid 1px #e0e0e0;
            line-height: 44px;
            display: flex;
            flex-direction: row;
            .btn-default {
                flex: 1;
                color: #41a6f0;
                font-size: 15px;
                text-align: center;
                &:active {
                    background: darken(#fff, 5%);
                }
                &:first-child {
                    border-right: solid 1px #e0e0e0;
                }
            }
        }
    }

    .modal-mask {
        position: absolute;
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        top: 0;
        z-index: 999;
        left: 0;
        background-color: rgba(0, 0, 0, 0.3);
    }

    .modal-content {
        position: absolute;
        width: 100%;
        height: 100%;
        z-index: 1000;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        top: 0;
        left: 0;
    }

</style>